package com.aek.aekdroid;

import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;

public class UpdateChecker extends IntentService {

	public static final String TAG = "UpdateChecker";
	public static final String NEW_VERSION = "com.aek.aekdroid.NEW_VERSION";
	public static final String RECEIVE_NOTIFICATIONS = "com.aek.aekdroid.RECEIVE_NOTIFICATIONS";
	private NotificationManager notificationManager;
	private Notification notification;

	public UpdateChecker() {
		super(TAG);
		MyLog.d(TAG, "onCreate");
	}

	@Override
	protected void onHandleIntent(Intent intent) {
		MyLog.d(TAG, "onHandleIntent");
		this.notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		this.notification = new Notification(R.drawable.ic_notify_match, "", 0);
		AekDroidApplication aek = (AekDroidApplication) getApplication();
		// WebAekDroid webAekDroid = aek.getWebAekDroid();
		// if (webAekDroid.isConnected) {
		String strVersion = intent.getStringExtra(NEW_VERSION);
		String latestVersion = aek.getLatestVersion(AekDroidApplication.newVersion);
		intent = new Intent(ScheduleActivity.APP_UPDATE);
		intent.putExtra(NEW_VERSION, latestVersion);
		sendBroadcast(intent, RECEIVE_NOTIFICATIONS);
		if (latestVersion != null) {
			sendUpdateNotification(latestVersion);
		}
		// } else {
		// if (intent.getBooleanExtra("manual", false)) {
		// Toast.makeText(this, R.string.notConnected, Toast.LENGTH_LONG);
		// }
		// MyLog.e(TAG, "No connection to the internet");

		// }
	}

	private void sendUpdateNotification(String version) {
		MyLog.d(TAG, "Sending notification for application update : " + version);
		Intent intent = new Intent(this, ScheduleActivity.class);
		PendingIntent pendingIntent = PendingIntent.getActivity(this, -1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
		this.notification.when = System.currentTimeMillis();
		this.notification.flags = Notification.FLAG_AUTO_CANCEL;
		CharSequence notificationTitle = this.getText(R.string.msgVersionNotificationTitle);
		CharSequence notificationSummary = this.getString(R.string.msgVersionNotificationMessage, version);
		this.notification.setLatestEventInfo(this, notificationTitle, notificationSummary, pendingIntent);
		this.notificationManager.notify(0, this.notification);
		MyLog.d(TAG, "Send Notification");

	}

}
